package com.sf.marathon.soul.core.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.google.common.collect.Maps;

/**
 * web相关的公共工具类
 *
 * @author liutao
 * @create 2017-05-16 上午10:10
 */

public class WebUtils {

    static Logger logger = LoggerFactory.getLogger(WebUtils.class);

    /**
     *  定义私有构建函数，避免new方式的错误使用，只提供静态方法
     */
    private WebUtils() {
    }

    /**
     * 构建分页参数
     *
     * @param req
     * @param isForce 是否强制分页，为true，则前端没有分页参数会给默认分页参数
     * @return
     */
    public static void startPage(HttpServletRequest req, boolean isForce) {
        // 当前页数
        String pageNo = req.getParameter("page.current");
        // 页大小
        String pageSize = req.getParameter("page.size");
        int current = 1;
        int size = 10;
        boolean pageable = StringUtils.isNotEmpty(pageNo) && StringUtils.isNotEmpty(pageSize);
        if (pageable) {
            current = Integer.parseInt(pageNo);
            size = Integer.parseInt(pageSize);
        }

        if (pageable || isForce) {
            PageHelper.startPage(current, size);
        } else {
            PageHelper.setPagination(null);
        }
    }

    public static void startPage(HttpServletRequest req) {
        WebUtils.startPage(req, true);
    }


    /**
     * 结束分页，进行资源释放
     */
    public static void endPage() {
        PageHelper.remove();
    }

    /**
     * 获取分页总数
     */
    public static int freePageTotal() {
        int total = PageHelper.getTotal();
        PageHelper.remove();
        return total;
    }

    /**
     * 构建查询map参数
     *
     * @param req
     * @return
     */
    public static Map<String, Object> buildParams(HttpServletRequest req) {
        return buildParams(req, false);
    }

    /**
     * 构建查询map参数
     *
     * @param req
     * @param convertToUnderline 转换成下划线
     * @return
     */
    public static Map<String, Object> buildParams(HttpServletRequest req, boolean convertToUnderline) {
        Map<String, Object> retParams = Maps.newHashMap();

        return retParams;
    }
}
